package 请求客户端;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 25228
 * Date: 2024-12-16
 * Time: 16:41
 */



public class HttpGetter {
    private String baseURL;

    public HttpGetter(String peer) {
        this.baseURL = "http://" + peer +  "/OOPCache/";
    }

    public String get(String group, String key) {
        try {
            // 构建完整的 URL
            URL url = new URL(baseURL + group + "/" + key);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法
            connection.setRequestMethod("GET");

            // 设置请求属性
            connection.setRequestProperty("Accept", "*/*");
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 11; Windows NT 5.1)");

            // 其他配置
            connection.setUseCaches(false);
            connection.setConnectTimeout(5000);

            // 发送 GET 请求
            connection.connect();

            // 处理响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) { // 成功
                InputStream in = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine())!= null) {
                    response.append(line).append("\n");
                }
                reader.close();
                return response.toString();
            } else {
                System.out.println("Failed : HTTP error code : " + responseCode);
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}